package com.example.bgxqmanage.mapper;

import com.example.bgxqapi.domain.dao.Activity;
import com.example.bgxqapi.domain.dto.SquareActivity;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;


/**
 * @author lizijian
 */
@Mapper
public interface ActivityDao {

  /**
   * 获取指定id动态
   *
   * @param id
   * @return
   */
  @Select("SELECT * FROM activity WHERE id = #{id}")
  Activity getActivityById(int id);


  /**
   * 删除指定id动态
   *
   * @param id 动态id
   */
  @Delete("UPDATE activity SET is_deleted =1 WHERE id = #{id}")
  void delete(int id);

  /**
   * 查询热门动态
   * @param userId
   * @return
   */
  @Results({@Result(property = "publisher.isAttention", column = "isAttention"),
      @Result(property = "publisher.username", column = "username"),
      @Result(property = "publisher.id", column = "user_id"),
      @Result(property = "publisher.avatar", column = "avatar"),
      @Result(property = "publisher.isVerify", column = "isVerify"),
      @Result(property = "publisher.sex", column = "sex"),
      @Result(property = "publisher.isVip",column = "isVip")})
  @Select("SELECT activity.*,(SELECT COUNT(*) FROM user_vip WHERE user_id = activity.user_id AND deadline > NOW()) AS isVip,(SELECT sex FROM `user` WHERE id = activity.user_id ) AS sex,(SELECT COUNT(*) FROM user_verify WHERE user_verify.user_id = activity.user_id AND user_verify.is_passed=1) AS isVerify,(SELECT COUNT(*) FROM activity_like WHERE user_id = #{userId} AND activity_id =activity.id LIMIT 1) AS isLiked,(SELECT COUNT(*) FROM user_attention WHERE user_id = #{userId} AND attention_user_id =activity.user_id) AS isAttention,(SELECT username FROM `user` WHERE id = activity.user_id ) AS username,(SELECT avatar FROM `user` WHERE id= activity.user_id) AS avatar "
      + " FROM activity WHERE is_deleted=0  AND visibility = 0  ORDER BY hot DESC")
  List<SquareActivity> getHotActivity(int userId);

  /**
   * 获取热门前十的动态
   * @return 动态id数组
   */
  @Select("SELECT activity.id FROM activity WHERE is_deleted=0  AND visibility = 0  ORDER BY hot DESC LIMIT 10")
  List<Integer> getHotActivityId();

  /**
   * 减少热门动态热度
   */
  @Update("<script>UPDATE activity SET hot = hot -#{reduceHot} WHERE id IN (<foreach collection = 'list' item='item' separator=','>#{item}</foreach>)</script>")
  void reduceHotActivityHot(@Param("list") List<Integer> hotActivityIds,@Param("reduceHot") int reduceHot);


}
